#include "bcrypt.h"
#include <crypt.h>
#include <unistd.h>
#include <random>
#include <sstream>
#include <string>

// Simple bcrypt implementation using crypt with $2b$ prefix
std::string hash_password(const std::string& password) {
    // Generate a random salt
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 63);
    
    // Base64 characters for bcrypt salt
    const char* base64_chars = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
    std::string salt = "$2b$10$";
    for (int i = 0; i < 22; i++) {
        salt += base64_chars[dis(gen) % 64];
    }
    
    // Hash the password with the salt
    char* hashed = crypt(password.c_str(), salt.c_str());
    
    // Clean up sensitive data
    // Note: In a real implementation, we would need to be more careful about
    // clearing the memory, but for this example, we'll just return the hash
    return std::string(hashed);
}

bool verify_password(const std::string& password, const std::string& hash) {
    // Hash the provided password with the same salt as the stored hash
    char* hashed = crypt(password.c_str(), hash.c_str());
    
    // Compare the hashes
    if (hashed == nullptr) {
        return false;
    }
    
    return hash == std::string(hashed);
}